from datetime import datetime, timedelta

from flask import Blueprint, request, jsonify, g
from sqlalchemy import func, desc

from extensions import db
from models import User, UserRole, RequestRecord, CostRecord, ConversationFile
from permissions import admin_required, super_admin_required
from config import Config
from services.conversation_file_service import ConversationFileService

admin_bp = Blueprint('admin', __name__, url_prefix='/api/admin')


@admin_bp.route('/users', methods=['GET'])
@admin_required
def get_all_users():
    """获取所有用户列表（管理员功能）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        role_filter = request.args.get('role', '')

        # 构建查询
        query = User.query

        # 搜索过滤
        if search:
            query = query.filter(
                db.or_(
                    User.username.contains(search),
                    User.email.contains(search)
                )
            )

        # 角色过滤
        if role_filter:
            try:
                role_enum = UserRole(role_filter)
                query = query.filter(User.role == role_enum)
            except ValueError:
                pass

        # 分页
        users = query.order_by(desc(User.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )

        return jsonify({
            'users': [user.to_dict() for user in users.items],
            'total': users.total,
            'pages': users.pages,
            'current_page': page,
            'per_page': per_page
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/conversations', methods=['GET'])
@admin_required
def get_all_conversations():
    """获取所有对话文件记录（管理员功能）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        user_id = request.args.get('user_id', type=int)
        
        # 构建查询
        query = ConversationFile.query
        
        if user_id:
            query = query.filter_by(user_id=user_id)
        
        # 分页
        conversations = query.order_by(desc(ConversationFile.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'conversations': [conv.to_dict() for conv in conversations.items],
            'total': conversations.total,
            'pages': conversations.pages,
            'current_page': page,
            'per_page': per_page
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/conversations/stats', methods=['GET'])
@admin_required
def get_conversation_stats():
    """获取对话文件统计信息（管理员功能）"""
    try:
        conversation_service = ConversationFileService()
        
        # 获取全局统计
        global_stats = conversation_service.get_storage_stats()
        
        # 获取用户分布统计
        user_stats = db.session.query(
            ConversationFile.user_id,
            User.username,
            func.count(ConversationFile.id).label('conversation_count'),
            func.sum(ConversationFile.total_size).label('total_size')
        ).join(User, ConversationFile.user_id == User.id)\
         .group_by(ConversationFile.user_id, User.username)\
         .order_by(desc('conversation_count')).limit(10).all()
        
        return jsonify({
            'global_stats': global_stats,
            'top_users': [{
                'user_id': stat.user_id,
                'username': stat.username,
                'conversation_count': stat.conversation_count,
                'total_size': stat.total_size,
                'total_size_mb': round(stat.total_size / (1024 * 1024), 2) if stat.total_size else 0
            } for stat in user_stats]
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/conversations/<int:conversation_id>', methods=['DELETE'])
@admin_required
def delete_conversation(conversation_id):
    """删除对话文件（管理员功能）"""
    try:
        conversation_service = ConversationFileService()
        
        success = conversation_service.delete_conversation(conversation_id)
        
        if success:
            return jsonify({'message': 'Conversation deleted successfully'})
        else:
            return jsonify({'error': 'Conversation not found'}), 404
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/conversations/cleanup', methods=['POST'])
@super_admin_required
def cleanup_conversations():
    """清理对话文件（超级管理员功能）"""
    try:
        data = request.get_json()
        days_old = data.get('days_old', 30)  # 默认清理30天前的文件
        
        from datetime import datetime, timedelta
        cutoff_date = datetime.utcnow() - timedelta(days=days_old)
        
        # 查找要删除的对话
        old_conversations = ConversationFile.query.filter(
            ConversationFile.created_at < cutoff_date
        ).all()
        
        conversation_service = ConversationFileService()
        deleted_count = 0
        
        for conv in old_conversations:
            if conversation_service.delete_conversation(conv.id):
                deleted_count += 1
        
        return jsonify({
            'message': f'Successfully deleted {deleted_count} old conversations',
            'deleted_count': deleted_count,
            'cutoff_date': cutoff_date.isoformat()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/users/<int:user_id>', methods=['GET'])
@admin_required
def get_user_detail(user_id):
    """获取用户详细信息"""
    try:
        user = User.query.get_or_404(user_id)

        # 获取用户统计信息
        stats = {
            'total_requests': db.session.query(RequestRecord).filter_by(user_id=user_id).count(),
            'total_cost': db.session.query(func.sum(CostRecord.cost)).filter_by(user_id=user_id).scalar() or 0,
            'recent_requests': db.session.query(RequestRecord).filter_by(user_id=user_id).order_by(
                desc(RequestRecord.created_at)).limit(10).all()
        }

        user_data = user.to_dict()
        user_data['stats'] = {
            'total_requests': stats['total_requests'],
            'total_cost': float(stats['total_cost']),
            'recent_requests': [{
                'id': req.id,
                'query': req.query[:100] + '...' if len(req.query) > 100 else req.query,
                'model': req.model,
                'status': req.status,
                'created_at': req.created_at.isoformat()
            } for req in stats['recent_requests']]
        }

        return jsonify(user_data)

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
@admin_required
def update_user(user_id):
    """更新用户信息（管理员功能）"""
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()

        # 只有超级管理员可以修改管理员用户
        if user.is_admin() and not g.current_user.is_super_admin():
            return jsonify({'error': 'Only super admin can modify admin users'}), 403

        # 更新允许的字段
        if 'role' in data:
            try:
                new_role = UserRole(data['role'])
                # 只有超级管理员可以设置超级管理员角色
                if new_role == UserRole.SUPER_ADMIN and not g.current_user.is_super_admin():
                    return jsonify({'error': 'Only super admin can assign super admin role'}), 403
                user.role = new_role
            except ValueError:
                return jsonify({'error': 'Invalid role'}), 400

        if 'weekly_request_limit' in data:
            user.weekly_request_limit = data['weekly_request_limit']

        if 'balance' in data:
            user.balance = data['balance']

        if 'is_active' in data:
            user.is_active = data['is_active']

        if 'is_verified' in data:
            user.is_verified = data['is_verified']

        user.updated_at = datetime.utcnow()
        db.session.commit()

        return jsonify({
            'message': 'User updated successfully',
            'user': user.to_dict()
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/users/<int:user_id>/toggle-status', methods=['POST'])
@admin_required
def toggle_user_status(user_id):
    """切换用户激活状态"""
    try:
        user = User.query.get_or_404(user_id)

        # 只有超级管理员可以停用管理员用户
        if user.is_admin() and not g.current_user.is_super_admin():
            return jsonify({'error': 'Only super admin can modify admin users'}), 403

        user.is_active = not user.is_active
        user.updated_at = datetime.utcnow()
        db.session.commit()

        return jsonify({
            'message': f'User {"activated" if user.is_active else "deactivated"} successfully',
            'is_active': user.is_active
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/stats', methods=['GET'])
@admin_required
def get_admin_stats():
    """获取系统统计信息（管理员功能）"""
    try:
        # 用户统计
        total_users = User.query.count()
        active_users = User.query.filter_by(is_active=True).count()

        # 角色分布
        role_stats = db.session.query(
            User.role, func.count(User.id)
        ).group_by(User.role).all()

        # 请求统计
        total_requests = db.session.query(RequestRecord).count()
        today_requests = db.session.query(RequestRecord).filter(
            RequestRecord.created_at >= datetime.utcnow().date()
        ).count()

        # 本周请求统计
        week_start = datetime.utcnow() - timedelta(days=7)
        week_requests = db.session.query(RequestRecord).filter(
            RequestRecord.created_at >= week_start
        ).count()

        # 费用统计
        total_cost = db.session.query(func.sum(CostRecord.cost)).scalar() or 0

        # 模型使用统计
        model_stats = db.session.query(
            RequestRecord.model, func.count(RequestRecord.id)
        ).group_by(RequestRecord.model).all()

        return jsonify({
            'users': {
                'total': total_users,
                'active': active_users,
                'inactive': total_users - active_users,
                'role_distribution': {role.value: count for role, count in role_stats}
            },
            'requests': {
                'total': total_requests,
                'today': today_requests,
                'this_week': week_requests
            },
            'costs': {
                'total': float(total_cost)
            },
            'models': {
                model: count for model, count in model_stats
            }
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/requests', methods=['GET'])
@admin_required
def get_all_requests():
    """获取所有请求记录（管理员功能）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        user_id = request.args.get('user_id', type=int)
        model = request.args.get('model')
        status = request.args.get('status')

        # 构建查询
        query = db.session.query(RequestRecord)

        if user_id:
            query = query.filter_by(user_id=user_id)

        if model:
            query = query.filter_by(model=model)

        if status:
            query = query.filter_by(status=status)

        # 分页
        total = query.count()
        requests_items = query.order_by(desc(RequestRecord.created_at)).offset((page-1)*per_page).limit(per_page).all()
        
        # 计算总页数
        pages = (total + per_page - 1) // per_page

        return jsonify({
            'requests': [{
                'id': req.id,
                'user_id': req.user_id,
                'username': req.user.username if req.user else 'Unknown',
                'query': req.query[:200] + '...' if len(req.query) > 200 else req.query,
                'model': req.model,
                'status': req.status,
                'execution_time': req.duration,
                'created_at': req.created_at.isoformat(),
                'updated_at': req.completed_at.isoformat() if req.completed_at else req.created_at.isoformat()
            } for req in requests_items],
            'total': total,
            'pages': pages,
            'current_page': page,
            'per_page': per_page
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@admin_bp.route('/system/config', methods=['GET'])
@super_admin_required
def get_system_config():
    """获取系统配置（超级管理员功能）"""
    try:
        # 这里可以返回系统配置信息
        config = {
            'roles': [{
                'name': role.value,
                'permissions': UserRole.get_role_permissions(role)
            } for role in UserRole],
            'models': {
                'available': list(Config.MODEL_PLATFORM_MAP.keys()),
                'platform_map': Config.MODEL_PLATFORM_MAP
            }
        }

        return jsonify(config)

    except Exception as e:
        return jsonify({'error': str(e)}), 500